package edu.fudan.jwxt.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import edu.fudan.jwxt.Exception.ServiceException;
import edu.fudan.jwxt.annotation.Adminer;
import edu.fudan.jwxt.common.Constants;
import edu.fudan.jwxt.common.ResultBody;
import edu.fudan.jwxt.entity.Classroom;
import edu.fudan.jwxt.service.ClassroomService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/classrooms")
public class ClassRoomController {

    @Autowired
    private ClassroomService classroomService;

    @GetMapping
    public ResultBody ListAll(){
        List<Classroom> classroomList =  classroomService.list();

        return ResultBody.success(classroomList);
    }


    @GetMapping("/{id}")
    public ResultBody getById(@PathVariable int id){
        Classroom classroom = classroomService.getById(id);

        return ResultBody.success(classroom);
    }

    //TODO: 用户权限检查
    @PostMapping("/insert")
    public ResultBody insertRoom(@RequestBody Classroom classroom){
        LambdaQueryWrapper<Classroom> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Classroom::getName,classroom.getName());
        long count = classroomService.count(queryWrapper);

        if(count != 0)
            throw new ServiceException(Constants.CODE_600,"教室已存在");

        classroomService.save(classroom);

        return ResultBody.success();
    }

    //TODO: 用户权限检查
    @PostMapping("/update")
    public ResultBody updateRoom(@RequestBody Classroom classroom){
        boolean flag = classroomService.updateById(classroom);

        if(flag)
            return ResultBody.success();
        else
            return ResultBody.error(Constants.CODE_600,"教室不存在");
    }

    //TODO: 用户权限检查
    @DeleteMapping("/{id}")
    public ResultBody deleteRoom(@PathVariable int id){
        boolean flag = classroomService.removeById(id);

        if(flag)
            return ResultBody.success();
        else
            return ResultBody.error(Constants.CODE_600,"教室不存在");
    }

    //批量删除
    //TODO: 用户权限检查
    @PostMapping("/delete")
    public ResultBody DeleteList(@RequestBody List<Classroom> classrooms){

        int failCount = 0;
        for(Classroom classroom : classrooms){
            try {
                classroomService.removeById(classroom.getId());
            }catch (Exception e){
                failCount++;
            }
        }
        if(failCount == 0)
            return ResultBody.success();
        else
            return ResultBody.error(Constants.CODE_600,"有部分教室无法删除");
    }

}
